package com.heima.Serivce.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heima.Mapper.WemediamaterialChannelMapper;
import com.heima.Serivce.WemediamaterialChannelService;
import com.heima.model.Admin.Dtos.ChannelDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.wemedia.pojos.WmChannel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class WemediamaterialChannelservice implements WemediamaterialChannelService {
    @Autowired
    WemediamaterialChannelMapper wemediamaterialChannelMapper;

//    查询频道
    @Override
    public ResponseResult GetChannel(ChannelDto channelDto) {
        QueryWrapper<WmChannel> wrapper=new QueryWrapper<>();
        IPage<WmChannel> iPage=new Page<>();
        if(channelDto!=null)
        {
//            模糊查询
            if(channelDto.getName()!=null)
                wrapper.like("name",channelDto.getName());
//            按照创建时间倒序排序
            wrapper.orderByDesc("created_time");
//            分页查询
            iPage.setSize(channelDto.getSize());
            iPage.setPages(channelDto.getPage());
        }
        IPage<WmChannel> channelIPage = wemediamaterialChannelMapper.selectPage(iPage, wrapper);
        List<WmChannel> records = channelIPage.getRecords();
        return ResponseResult.okResult(records);
    }

//    删除Channel
    @Override
    public ResponseResult DeleteChannel(Integer id) {
        wemediamaterialChannelMapper.deleteById(id);
        return ResponseResult.okResult("Channel成功删除");
    }

//    添加频道
    @Override
    public ResponseResult SaveChannel(WmChannel wmChannel) {
        QueryWrapper<WmChannel> wrapper=new QueryWrapper<>();
        wrapper.eq("name",wmChannel.getName());
        WmChannel one = wemediamaterialChannelMapper.selectOne(wrapper);
        if(one!=null)
            return ResponseResult.errorResult(201,"数据已经存在");
        wemediamaterialChannelMapper.insert(wmChannel);
        return ResponseResult.okResult("Channel成功添加");
    }

//    修改频道
    @Override
    public ResponseResult UpdateChannel(WmChannel wmChannel) {
        WmChannel channel = wemediamaterialChannelMapper.selectById(wmChannel.getId());
        if(channel==null)
            return ResponseResult.errorResult(404,"数据不存在");
        wemediamaterialChannelMapper.updateById(wmChannel);
        return ResponseResult.okResult("Channel修改成功");
    }
}
